#include "CacheManager.h"
#include <iostream>
#include <mutex>
#include <sys/timerfd.h>

CacheManager *CacheManager::_instance = nullptr;

CacheManager::CacheManager(): _cacheList(4), _cacheUpdateList(4), _mutexList(4){

}

CacheManager::~CacheManager(){

}

CacheManager *CacheManager::getInstance(){
    if(!_instance){
        _instance = new CacheManager();
    }
    return _instance;
}

//从磁盘文件中读取缓存信息
void CacheManager::initCache(size_t num, const string &filename){
 
}

//获取某个缓存
LRUCache &CacheManager::getCache(size_t idx){
    return _cacheList[idx];
}

mutex &CacheManager::getMutex(size_t idx){
    return _mutexList[idx];
}

//定时更新所有的缓存
void CacheManager::updateCache(){
    for(size_t i = 0; i < _cacheList.size(); i++){
        lock_guard<mutex> lock(_mutexList[i]);
        _cacheUpdateList[i] = _cacheList[i];
    }
    //以第一个缓存作为基准缓存
    LRUCache baseCache = _cacheUpdateList[0];
    //从第二个缓存开始遍历，把更新的数据写入基准缓存
    for(size_t i = 1; i < _cacheUpdateList.size(); i++){
        /* cout << "第一个循环" << endl; */
        list<pair<string, string>> &pendingList = _cacheUpdateList[i].getPendingUpdateList();
        for(auto &i: pendingList){
            baseCache.addElement(i.first, i.second);
        }
    }
    //从第一个缓存开始，把更新后的新缓存复制给旧缓存
    for(size_t i = 0; i < _cacheList.size(); i++){
        /* cout << "第二个循环" << endl; */
        _cacheUpdateList[i].update(baseCache);
    }
    for(size_t i = 0; i < _cacheList.size(); i++){
        lock_guard<mutex> lock(_mutexList[i]);
        //直接交换两个vector缓存数组的数据，提高效率
        swap(_cacheList[i], _cacheUpdateList[i]);
    }
}
